After using RXJS, I have loved using tap operator which essentially allows you to peek into a chain without modifying it. I would love to do the same with a fluent array chain. This can be done by adding a function to the prototype as shown below, but is there a way to do the same or similar using standard array methods? Also, is there any developments on adding this to the specification (or rationale as to why not to have it)?
I know I could just break up the chain into multiple variables (i.e., const oddNumbers...) but that sometimes doesn't fit the style I am going for.
Array.prototype.tap = function(fn){
const arr = Object(this)
fn(arr);
return arr
}
const numbers = [0,1,2,3,4,5];
const sumOfOdds = numbers.filter(x=>x%2)
.tap(oddNumbers => console.log(oddNumbers))
.reduce((acc,cur)=>acc+cur,0)
console.log(sumOfOdds);
One way to do this using map would be the following, but it is called n times and is not super pretty.
Array.prototype.tap = function(fn){
const arr = Object(this)
fn(arr);
return arr
}
const numbers = [0,1,2,3,4,5];
const sumOfOdds = numbers.filter(x=>x%2)
.map((val, i, arr) => {
if (i === 0) // run once
console.log(arr);
return val;
})
.reduce((acc,cur)=>acc+cur,0)
console.log(sumOfOdds);
A .map which calls the other function inside the callback can do the same thing.
const numbers = [0,1,2,3,4,5];
const fn = oddNumber => console.log(oddNumber);
const sumOfOdds = numbers.filter(x=>x%2)
.map(num => (fn(num), num))
.reduce((acc,cur)=>acc+cur,0)
console.log(sumOfOdds);
or if you don't like the comma operator
const numbers = [0,1,2,3,4,5];
const fn = oddNumber => console.log(oddNumber);
const sumOfOdds = numbers.filter(x=>x%2)
.map(num => { fn(num); return num; })
.reduce((acc,cur)=>acc+cur,0)
console.log(sumOfOdds);